#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

Log lg;

void Usage(char *proc)
{
  std::cout << "\n\rUsage: " << proc << "port[1024+]\n"
            << std::endl;
}

int main(int argc, char *argv[])
{
  if (argc != 3)
  {
    Usage(argv[0]);
    return 1;
  }

  std::string serverip = argv[1];
  uint16_t serverport = std::stoi(argv[2]);
  while (true)
  {
    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
      lg(Fatal, "socket create error, errno: %d, errmsg: %s", errno, strerror(errno));
      exit(1);
    }

    // 2. 不需要显示的绑定,直接connect
    struct sockaddr_in server;

    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    socklen_t len = sizeof(server);

    bool isNotConnect = false;
    int num = 5;
    do
    {
      int cnt = connect(sockfd, (const sockaddr *)&server, len);
      if (cnt < 0)
      {
        lg(Fatal, "connect error, errno: %d, errmsg: %s, cnt: %d", errno, strerror(errno), num);
        num--;
        isNotConnect = true;
        sleep(1);
      }
      else
      {
        // isNotConnect = false;
        break;
      }
    } while (num && isNotConnect);

    if (num == 0)
    {
      std::cout << "user unoline....." << std::endl;
      close(sockfd);
      break;
    }

    char buffer[4096];

    memset(buffer, 0, sizeof(buffer));
    std::string message;
    std::cout << "Please Enter@ ";
    getline(std::cin, message);

    int n = write(sockfd, message.c_str(), message.size());
    if (n < 0)
    {
      std::cout << "write error ......." << std::endl;
      close(sockfd);
    }
    n = read(sockfd, buffer, sizeof(buffer));
    if (n > 0)
    {
      buffer[n] = 0;
      std::cout << buffer << std::endl;
    }
    close(sockfd);
  }

  return 0;
}